from flask import request, Blueprint, send_file
import os
from config.config import serverPath, domain
from model.navbg import getBackgroundImage, delBackground, addBackground

navbg = Blueprint('navbg', __name__)


@navbg.route('/upnavbg', methods=['POST'])
def upload_user_file():
    if 'file' not in request.files:
        return 'No file selected'
    file = request.files['file']
    if file.filename == '':
        return 'No file selected'
    if file:
        file.save(os.path.join(serverPath, 'navbg/', file.filename))
        return domain + "/navbg/" + file.filename


@navbg.route('/navbg/<filename>')
def get_user_image(filename):
    # 构建图片文件的完整路径
    image_path = os.path.join(serverPath + '/navbg/' + filename)
    # 使用 send_file 函数发送图片文件
    return send_file(image_path, mimetype='image/jpeg')


@navbg.route('/getnavbglist', methods=['POST', 'GET'])
def get_nav_bg_list():
    if request.method == 'GET':
        category = request.args.get("category")
        isHome = request.args.get("ishome")
        info = getBackgroundImage(category, isHome)
        return info
    else:
        return "不支持POST方法"


@navbg.route("/delbackground", methods=["POST", "GET"])
def del_backround():
    if request.method == "POST":
        data = request.get_json()
        userid = data['userid']
        navid = data['navid']
        token = data["token"]
        info = delBackground(userid, navid, token)
        return info
    else:
        return "不支持GET方法"


@navbg.route("/addbackground", methods=['POST', 'GET'])
def add_background():
    if request.method == "POST":
        data = request.get_json()
        userid = data['userid']
        category = data['category']
        img = data["img"]
        token = data["token"]
        info = addBackground(userid, category, img, token)
        return info
    else:
        return "不支持GET方法"
